package com.chorye.function.schedule.component;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

/**
 * 自定义AutowiringSpringBeanJobFactory，解决spring不能在quartz中注入bean的问题
 *
 * @author Chorye
 */
public final class QuartzJobFactory extends SpringBeanJobFactory implements
        ApplicationContextAware {

    /**
     * 自动装配能力Bean工厂
     */
    private transient AutowireCapableBeanFactory beanFactory;

    /**
     * 设置Spring应用上下文
     *
     * @param context Spring应用上下文
     */
    @Override
    public void setApplicationContext(final ApplicationContext context) {
        // 从Spring应用上下文中获取自动装配能力Bean工厂
        beanFactory = context.getAutowireCapableBeanFactory();
    }

    /**
     * 创建任务实例
     *
     * @param bundle 触发器触发工具
     * @return 定时任务
     * @throws Exception 创建任务实例异常
     */
    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        // 调用父类的创建任务实例方法
        final Object job = super.createJobInstance(bundle);
        // 在自动装配能力Bean工厂中注入定时任务实例
        beanFactory.autowireBean(job);
        return job;
    }
}